package com.event.gateway.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 图片路径配置
 * 负责查找eventsys根目录并设置路径属性
 */
@Configuration
@Slf4j
public class ImagePathConfig {

    @Value("${image.base-dir:eventsys}")
    private String baseDir;
    
    // 使用缓存存储已查找到的目录路径
    private static final ConcurrentHashMap<String, String> DIR_CACHE = new ConcurrentHashMap<>();
    
    // 使用原子引用存储根目录路径，确保线程安全
    private static final AtomicReference<String> ROOT_DIR_REF = new AtomicReference<>();
    
    @PostConstruct
    public void init() {
        String eventsysPath = findEventsysRootDir();
        if (eventsysPath != null) {
            ROOT_DIR_REF.set(eventsysPath);
            System.setProperty("image.root-dir", eventsysPath);
            log.info("已设置eventsys根目录: {}", eventsysPath);
        } else {
            log.warn("无法找到eventsys目录，使用当前目录作为根目录");
        }
    }
    
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        // 设置系统属性优先
        configurer.setLocalOverride(false);
        
        // 添加默认属性
        Properties properties = new Properties();
        properties.setProperty("image.root-dir", System.getProperty("user.dir"));
        configurer.setProperties(properties);
        
        return configurer;
    }
    
    /**
     * 查找eventsys根目录
     * 先向上查找，再向下查找，最后搜索磁盘
     */
    private String findEventsysRootDir() {
        // 先检查缓存
        String cacheKey = baseDir;
        String cachedPath = DIR_CACHE.get(cacheKey);
        if (cachedPath != null) {
            return cachedPath;
        }
        
        String currentDir = System.getProperty("user.dir");
        File currentFile = new File(currentDir);
        
        // 首先，向上查找到eventsys目录
        while (currentFile != null) {
            if (currentFile.getName().equals(baseDir)) {
                // 缓存并返回结果
                DIR_CACHE.put(cacheKey, currentFile.getAbsolutePath());
                return currentFile.getAbsolutePath();
            }
            currentFile = currentFile.getParentFile();
        }
        
        // 其次，尝试从当前目录向下找
        File startDir = new File(currentDir);
        File result = findDirectoryDown(startDir, baseDir, 3); // 限制搜索深度
        if (result != null) {
            // 缓存并返回结果
            DIR_CACHE.put(cacheKey, result.getAbsolutePath());
            return result.getAbsolutePath();
        }
        
        // 最后，如果在Windows环境，从磁盘根开始查找（有深度限制）
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            for (File root : File.listRoots()) {
                // 只搜索C盘和D盘等常用盘符
                if (root.getAbsolutePath().startsWith("C:") || 
                    root.getAbsolutePath().startsWith("D:") ||
                    root.getAbsolutePath().startsWith("E:")) {
                    
                    result = findDirectoryDown(root, baseDir, 2); // 限制搜索深度
                    if (result != null) {
                        // 缓存并返回结果
                        DIR_CACHE.put(cacheKey, result.getAbsolutePath());
                        return result.getAbsolutePath();
                    }
                }
            }
        }
        
        // 返回当前目录作为默认值
        return currentDir;
    }
    
    /**
     * 向下递归查找目录（有最大深度限制）
     */
    private File findDirectoryDown(File startDir, String targetName, int maxDepth) {
        if (startDir == null || !startDir.exists() || !startDir.isDirectory() || maxDepth <= 0) {
            return null;
        }
        
        if (startDir.getName().equals(targetName)) {
            return startDir;
        }
        
        File[] children = startDir.listFiles();
        if (children != null) {
            for (File child : children) {
                if (child.isDirectory()) {
                    if (child.getName().equals(targetName)) {
                        return child;
                    }
                    
                    // 递归查找，减少深度
                    File result = findDirectoryDown(child, targetName, maxDepth - 1);
                    if (result != null) {
                        return result;
                    }
                }
            }
        }
        
        return null;
    }
    
    /**
     * 获取缓存的根目录路径
     */
    public static String getRootDir() {
        return ROOT_DIR_REF.get();
    }
} 